package net.quanter.shield.mail;

import net.quanter.shield.mail.config.AuthConfig;
import net.quanter.shield.mail.params.MailMessageParam;
import net.quanter.shield.mail.params.MailServerParam;

import javax.mail.*;
import javax.mail.internet.*;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;


/**
 * 邮件发送工具类
 *
 * @author wanglaoshi
 */
public class MailSender {

    private final MailServerParam param;
    private final Properties prop;
    private final AuthConfig auth;

    /**
     * 私有化构造函数
     *
     * @param param 邮件服务器参数
     */
    public MailSender(MailServerParam param) {
        this.param = param;
        this.prop = wrapProperties(param);
        this.auth = new AuthConfig(param.getUsername(), param.getPassword());
    }

    /**
     * 单个发送邮件，发送完就关闭连接
     *
     * @param mailMessageParam 发送邮件内容
     * @param receiver         接受者邮件
     * @param debug            是否debug
     * @throws Exception 发送邮件异常
     */
    public void send(MailMessageParam mailMessageParam, String receiver, boolean debug) throws Exception {
        Set<String> receiverSet = new HashSet<String>();
        receiverSet.add(receiver);
        batchSend(mailMessageParam, receiverSet, debug);
    }

    /**
     * 批量发送邮件，发送完就关闭连接
     *
     * @param mailMessageParam 发送邮件内容
     * @param receiverSet      接受者邮件列表
     * @param debug            是否debug
     * @throws Exception 发送邮件异常
     */
    public void batchSend(MailMessageParam mailMessageParam, Set<String> receiverSet, boolean debug) throws Exception {
        // 构建邮件会话
        Session mailSession = Session.getDefaultInstance(prop, auth);
        mailSession.setDebug(debug);

        // 构建邮件消息
        Message mailMessage = new MimeMessage(mailSession);
        // 设置昵称
        String nick = MimeUtility.encodeText(mailMessageParam.getSenderNickname());
        Address from = new InternetAddress(nick + " <" + param.getUsername() + ">");
        mailMessage.setFrom(from);
        // 设置邮件主题
        mailMessage.setSubject(mailMessageParam.getSubject());

        // 设置邮件内容
        Multipart mainPart = new MimeMultipart();
        // 内容是可以包含html
        BodyPart bodyPart = new MimeBodyPart();
        bodyPart.setContent(mailMessageParam.getContent(), mailMessageParam.getEncoding());
        mainPart.addBodyPart(bodyPart);
        mailMessage.setContent(mainPart);

        Set<Address> addressSet = new HashSet<Address>();
        for (String receiver : receiverSet) {
            // 设置邮件接收者
            Address to = new InternetAddress(receiver);
            addressSet.add(to);
        }
//        mailMessage.setRecipient(Message.RecipientType.TO, to);
        Address[] addresses = new Address[addressSet.size()];
        addressSet.toArray(addresses);
        // 发送邮件
        Transport.send(mailMessage, addresses);
    }

    private static Properties wrapProperties(MailServerParam sender) {
        Properties prop = new Properties();
        prop.put("mail.smtp.host", sender.getSmtpHost());
        prop.put("mail.smtp.port", sender.getSmtpPort());
        prop.put("mail.smtp.auth", "true");

        // 开启ssl
        if (sender.isSsl()) {
            prop.put("mail.smtp.port", sender.getSmtpPort());
            prop.put("mail.smtp.socketFactory.port", sender.getSmtpPort());
            prop.put("mail.smtp.socketFactory.fallback", "false");
            prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        }
        return prop;
    }

}
